import React, { Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import {
    Table, Card, Button, List,
    Popover, Divider, Avatar,
    Spin, Select, Icon, Input,Menu,Dropdown,
    message, Form, Row, Popconfirm,
    Col,InputNumber,Modal,Cascader,Checkbox
} from 'antd';
import HeaderTab from '@/components/HeaderTab';
import styles from './index.less';
import ChangeLebal from './changeLebal';
import ChangeClassify from './changeClassify';
import ChangePrice from './changePrice';
import ChangeStock from './changeStock';

const Option = Select.Option;

const FormItem = Form.Item;
@Form.create()

class Pagination extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pagination: {
        showSizeChanger: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSize: 10,
        total: 0,
      },
      expandForm: false,
      groupName: '',
      labelName: '',
      label: [],
      pageIndex: 1,
      GroupIds: null, //分类
      tagValue: null, // 标签
      productName: '', //名称
      sortName: 'CreateTime', //默认 saleprice
      sort: 'Desc', //默认 Asc
      selectedUserIds: [],
      loading: true,
      btnLoading: false,
      btnLoading2: false,
      firstLoading: true,
      searchLoading: false,
      selectedRows:[],
      isChecked:false,
      indeterminate: false,
      tabs: [
        {
          title: '出售中',
          key: `/${window.storeId}/goods/onsale`,
          // disabled: true
        },
        {
          title: '已售罄',
          key: `/${window.storeId}/goods/soldout`,
        },
        {
          title: '仓库中',
          key: `/${window.storeId}/goods/instock`,
        },
      ],
    };
  }
  componentWillMount() {
    window.Isoption = false;
  }

  componentDidMount() {
      this.getSearchSoldOutProductListWithPage();
      this.GetProductGroupList();
      this.GetTagList();
      window.Isoption = true;
  }

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
        GroupIds: null,
        TagIds:null,
        productName: '',
    });
  };

      //标签选择
      handleChange = value => {
        this.setState({
            TagIds: value
        })}

    // 分类选择
    onChangeTreeData = (value) => {
        let arr = [];
        value&&value.map(item => {
            let id = item.split('0-0-')[1];
            arr.push(id);
        })
        this.setState({value, GroupIds: arr});
        this.props.form.setFieldsValue({
            tProps: value
        });
    }

     //分类树输入框输入
     onSearchTreeData = (searchValue) => {
        this.setState({
            GroupIds: [10000000000]
        })
    }

  // 筛选
  handleSearch = e => {
    e.preventDefault();
    const {dispatch,form} = this.props;
    this.setState({
        searchLoading: true,
        loading: true
    })
    form.validateFields((err, values) => {
        if(err) return;
        const datas = {
            ...values,
            GroupIds: values.GroupIds[1]===0?[0]:values.GroupIds[1]?[values.GroupIds[1]]:[],
        }
        this.getSearchSoldOutProductListWithPage({...datas});
    })
  };


  // 获取已售完列表
  getSearchSoldOutProductListWithPage = params => {
    const { dispatch } = this.props;
    const {GroupIds, pageIndex} = this.state;
    dispatch({
        type: 'pruductSellList/GetSearchSoldOutProductListWithPage',
        payload: {
            PageIndex: pageIndex,
            PageSize: this.state.pagination['pageSize'],
            ProductName: params&& params.ProductName?params.ProductName:'',
            GroupIds: params&& params.GroupIds?params.GroupIds:[], //商品分类
            TagIds: params&& params.TagIds?params.TagIds:[], //	商品标签
            SortName: this.state.sortName,
            Sort: this.state.sort,
        },
        callBack: {
            success: res => {
                if(res.Code ===0){
                    this.setState({
                        loading: false,
                        firstLoading:false,
                        searchLoading: false,
                        isChecked: false,
                        selectedUserIds: [],
                        indeterminate: false,
                        pagination: {
                            pageSize: this.state.pagination['pageSize'],
                            current: pageIndex,
                            total: res.Data.Total,
                            showSizeChanger: true,
                            showTotal: total => `共 ${total} 条记录`,
                          },
                    });
                }
            },
            error: res => {
                message.error(res.Msg);
                this.setState({
                  indeterminate: false,
                })

            },
        },
    });
  }


  // 获取分组
  GetProductGroupList =() => {
    const {dispatch} = this.props;
    dispatch({
      type: 'pruductSellList/GetProductGroupList',
      payload: {
        name: this.state.groupName,
      },
    })
  }

  // 获取标签
  GetTagList =() => {
    const { dispatch } = this.props;
    dispatch({
      type: 'pruductSellList/GetTagList',
      payload: {
        name: this.state.labelName,
      },
    })
  }

  // tab切换
  onTableChange =(pagination, filters, sorter) => {
    this.setState(
        {
          loading: true,
          pagination: {
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showTotal: total => `共 ${total} 条记录`,
          },
          pageIndex: pagination.current,
        },
        () => {
            // 价格
            if (sorter.column && sorter.column.dataIndex === 'SalePrice') {
                if (sorter.order === 'ascend') {
                    this.setState({
                        sortName: 'SalePrice',
                        sort: 'Asc'
                    }, () => {
                        this.getSearchSoldOutProductListWithPage();
                    }
                )} if (sorter.order === 'descend') {
                    this.setState({
                        sortName: 'SalePrice',
                        sort: 'Desc'
                    }, () => {
                        this.getSearchSoldOutProductListWithPage();
                    }
                )}
            }
            // 库存
            if (sorter.column && sorter.column.dataIndex === 'Stock') {
                if (sorter.order === 'ascend') {
                    this.setState({
                        sortName: 'StockNum',
                        sort: 'Asc'
                    }, () => {
                        this.getSearchSoldOutProductListWithPage();
                    }
                )} if (sorter.order === 'descend') {
                    this.setState({
                        sortName: 'StockNum',
                        sort: 'Desc'
                    }, () => {
                        this.getSearchSoldOutProductListWithPage();
                    }
                )}
            }
            // 销量
            if (sorter.column && sorter.column.dataIndex === 'SaleNum') {
                if (sorter.order === 'ascend') {
                    this.setState({
                        sortName: 'SaleNum',
                        sort: 'Asc'
                    }, () => {
                        this.getSearchSoldOutProductListWithPage();
                    }
                )} if (sorter.order === 'descend') {
                    this.setState({
                        sortName: 'SaleNum',
                        sort: 'Desc'
                    }, () => {
                        this.getSearchSoldOutProductListWithPage();
                    }
                )}
            }
            // 排序
            if (sorter.column && sorter.column.dataIndex === 'Sort') {
                if (sorter.order === 'ascend') {
                    this.setState({
                        sortName: 'Sort',
                        sort: 'Asc'
                    }, () => {
                        this.getSearchSoldOutProductListWithPage();
                    }
                )} if (sorter.order === 'descend') {
                    this.setState({
                        sortName: 'Sort',
                        sort: 'Desc'
                    }, () => {
                        this.getSearchSoldOutProductListWithPage();
                    }
                )}
            } else {
                this.getSearchSoldOutProductListWithPage();
            }
        }
    )
  }

  // 头部商品状态切换
  onTabChange = id => {
    this.setState(
      {
        activeId: id,
      },
      () => {
        router.replace({
          pathname: `${id}`,
        });
      }
    );
  };

  releaseGoods = () => {
    router.replace({
      pathname: `/${window.storeId}/goods/releaseGoods`,
    });
  };

  handleVisibleChange = (visible) =>{
    const { dispatch} = this.props;
    if(visible){
        dispatch({
          type: 'orderPickUp/GetWxCode',
          callBack: {
            success: res => {
              if(res.Code==0){
                this.setState({
                  wxaUrl:res.Data.WxCodeUrl
                })
              }
            },
          },
        });
      }
  }

  showQRcode = data => {
    const {loading2} = this.props;
    return (
        <Spin spinning={loading2}>
          <div className="xkd-text-center">
            {this.state.wxaUrl ? (
              <div style={{width:240,minHeight:240}}>
                <Input value={`/pages/home/micropage?id=${data}`} className="xkd-mb8" />
                <img
                  src={`${cdnUrl + '/'+this.state.wxaUrl||'https://xkdsaas.oss-cn-shanghai.aliyuncs.com/MerChant/2905/1260/1508825223069.png'}`}
                  style={{ width: 240 }}
                />
              </div>
            ) : (
              <div style={{width:240,minHeight:240,lineHeight:'240px',textAlign:'center'}}>
                <span>未绑定小程序</span>
              </div>
            )}
          </div>
        </Spin >
      );
  };

  //点批量下架
  clickOffline =() => {
      const {selectedUserIds} = this.state;
      const { dispatch } = this.props;
      const that = this;
      if(selectedUserIds.length< 1) {
        message.error('请选择最少一个商品');
      }else {
          Modal.confirm({
            title: '确认下架?',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                dispatch({
                    type: 'pruductSellList/SetProductsOffline',
                    payload: selectedUserIds.toString(),
                    callBack: {
                        success: res => {
                          if (res.Code === 0) {
                            message.success('下架成功');
                            that.setState({
                                loading: true,
                                selectedUserIds:[]
                            },
                              () => {
                                  that.getSearchSoldOutProductListWithPage();
                              }
                            );
                          }
                        },
                        error: res => {
                          message.error(res.Msg);
                        },
                      },
                });
            }
          })
      }
  }

      // 更新
      refchData =()=> {
        this.setState({
            loading: true
        },
          () => {
              this.getSearchSoldOutProductListWithPage();
        });
   }

  //修改标签
  handleMenuClick = e => {
    const {selectedUserIds} = this.state;
    const action = e.item.props.children;
    if (action === '修改标签') {
      if(selectedUserIds.length> 0) {
        const title = '修改标签';
        const width = 320;
        this.changeLebal.show({width,title, selectedUserIds}, this.refchData)
       } else {
        message.error('请选择最少一个商品');
       }
    }
}

    //修改分类
    clickChangeClassfy=()=> {
        const {selectedUserIds} = this.state;
        if(selectedUserIds.length> 0) {
            const title = '修改分类';
            this.changeClassify.show({title, selectedUserIds}, this.refchData)
        } else {
            message.error('请选择最少一个商品');
        }
    }

    // 单个修改排序
    updateProductSort =(id, value) => {
        const { dispatch } = this.props;
        const {sort} = this.state;
        dispatch({
            type: 'pruductSellList/UpdateProductSort',
            payload: {
                id: id,
                sort: sort/1? sort: value/1
            },
            callBack: {
                success: res => {
                  if (res.Code === 0) {
                    message.success('修改成功');
                    this.setState({
                        sort:'Desc'
                        // loading: true
                    },
                      () => {
                          this.getSearchSoldOutProductListWithPage();
                      }
                    );
                  }
                },
                error: res => {
                  message.error(res.Msg);
                },
              },
        })
      }

      // 单个修改库存
      updateProductStock = (id, value) => {
        const { dispatch } = this.props;
        const {stock} = this.state;
        dispatch({
            type: 'pruductSellList/UpdateProductStock',
            payload: {
                ProductId: id,
                ProductSku: [
                    {
                        SkuId: id,
                        StockNum: stock/1 ? stock : value/1
                    }
                ]
            },
            callBack: {
                success: res => {
                  if (res.Code === 0) {
                    message.success('修改成功');
                    this.setState({
                        visible2: false
                        // loading: true
                    },
                      () => {
                          this.getSearchSoldOutProductListWithPage();
                      }
                    );
                  }
                },
                error: res => {
                  message.error(res.Msg);
                },
            },
        })
      }

      //多规格编辑框
      ChangePrice =(id) => {
        let { dispatch } = this.props;
        this.setState({
          btnLoading: true
         })
           dispatch({
               type: 'pruductSellList/GetProductSkuInfoByProductId',
               payload: {
                   id: id
               },
               callBack:  {
                   success: res => {
                       this.setState({
                           editPriceVisible: true,
                           ProductId: id,
                           btnLoading: false
                       })}
               }
       })}

       ChangeStock = id => {
        let { dispatch } = this.props;
        this.setState({
          btnLoading2: true
         })
        dispatch({
          type: 'pruductSellList/GetProductSkuInfoByProductId',
          payload: {
              id: id
          },
          callBack: {
              success: res => {
                this.setState({
                  editStockVisible: true,
                  ProductId: id,
                  btnLoading2: false
              })}
          }
      })}

      hasErrors =(fieldsError) =>{
        return Object.keys(fieldsError).some(field => fieldsError[field]);
      };

   //单个修改价格
   updateSProductPrice = (id, value) => {
    const {getFieldsError} = this.props.form;
    const { dispatch } = this.props;
    const {salePrice} = this.state;
    if(!this.hasErrors(getFieldsError())) {
        dispatch({
            type: 'pruductSellList/UpdateSProductPrice',
            payload: {
                ProductId: id,
                ProductSku: [
                    {
                        SkuId: id,
                        SalePrice: salePrice/1? salePrice: value
                    }
                ]
            },
            callBack: {
                success: res => {
                  if (res.Code === 0) {
                    message.success('修改成功');
                    this.setState({
                        visible: false
                        // loading: true
                    },
                      () => {
                          this.getSearchSoldOutProductListWithPage();
                      }
                    );
                  }
                },
                error: res => {
                  message.error(res.Msg);
                },
            },
        })
    }
  }

    // 跳转到商品编辑页
    editPage = (Id) => {
        router.replace({
            pathname: `/${window.storeId}/goods/editproduct/${Id}`,
        });
    }

    changeTreeData = (arr, arr2,index) => {
        let newArr=arr2||[];
        if(arr){
            for(let i=0;i<arr.length;i++){
                let item=arr[i];
                newArr.push({
                    value:item.Id,
                    label:item.Name,
                    disabled: item.SecondList?false: true,
                    children:[]
                });
                if(item.SecondList && item.SecondList.length> 0){
                    for(let j=0;j<item.SecondList.length;j++){
                        let item2=arr[i].SecondList[j];
                        newArr[i].children.push({
                            value:item2.Id,
                            label:item2.Name,
                            children:[]
                        })
                    }
                }
            }
        }
        return newArr;
     }

  renderAdvancedForm() {
    const {form: { getFieldDecorator},productTagList,productGroupList} = this.props;
    let options = this.changeTreeData(productGroupList,[],0)
    const {searchLoading} = this.state;
    return (
        <Form layout="inline">
        <Row>
          <Col span={8}>
            <FormItem label="商品名称">
            {getFieldDecorator('ProductName')(
                <Input className="xkd-width-per-100"/>
            )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="商品分类">
                {getFieldDecorator('GroupIds', {
                        initialValue: []
                    })(
                        <Cascader
                            options={options}
                            placeholder="不选则显示全部"
                            className="xkd-width-per-100"
                            popupClassName="popupClassName"
                            expandTrigger="hover"
                        />
                        // <TreeSelect {...tProps} className={styles.treeSelect}/>
                )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="商品标签">
                {getFieldDecorator('TagIds', {
                    initialValue: []
                })(
                    <Select
                        mode="multiple"
                        style={{  width: '100%'}}
                        placeholder="可多选"
                        onChange={this.handleChange}
                        >
                        {productTagList&&productTagList.map((item, index)=> (<Option key={index} value={item.id}>{item.name}</Option>))}
                   </Select>
                )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden'}}>
          <div className="screenNavButton">
            <Button type="primary" onClick={this.handleSearch} loading={searchLoading}>
              筛选
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    return this.renderAdvancedForm()
  }

     //行内编辑排序
     editSort(sort) {
        return (
            <div className={styles.classifyModal}>
              <p style={{marginBottom: 8}}>修改排序</p>
              <InputNumber
              min={0}
              max={9999999}
              defaultValue={sort/1}
              onChange={value => {
                  this.setState({ sort: value });
              }}
              />
        </div>
        )};

     // 单个修改库存
     editStock(stock) {
         return (
            <div className={styles.classifyModal}>
              <p style={{marginBottom: 8}}>修改库存</p>
              <InputNumber
                min={0}
                max={9999999}
                defaultValue={stock/1}
                onChange={value => {
                    this.setState({ stock: value });
                  }}
              />
          </div>
      )}

      // 单个修改价格
      editSalePrice(salePrice) {
        const {getFieldDecorator} = this.props.form;
          return (
              <Form>
                <div className={styles.classifyModal}>
                    <p style={{marginBottom: 8}}>修改价格</p>
                    <Form.Item>
                      {getFieldDecorator('inputNumber', {
                          initialValue: salePrice/1,
                          rules: [
                              {required: true, message: '请输入价格'},
                              {pattern: /^0\.([1-9]|\d[1-9])$|^[1-9]\d{0,8}\.\d{0,2}$|^[1-9]\d{0,8}$/, message: '不小于0.01,最多2位小数'}
                        ]
                      })(
                        <InputNumber
                        min={0}
                        max={9999999}
                        // defaultValue={salePrice/1}
                        onChange={value => {
                            this.setState({ salePrice: value });
                        }}
                        />
                      )
                   }
                   </Form.Item>
                </div>
              </Form>
      )}

//点击价格
clickQueryPriceData = (id, index)=>{
    let { dispatch } = this.props;
    this.setState({
     btnLoading: true
    })
       dispatch({
           type: 'pruductSellList/IsMultiProduct',
           payload: {
               id: id
           },
           callBack:  {
               success: res => {
                   if(res.Data) {
                    this.setState({
                        clickId: ''
                   })
                    dispatch({
                        type: 'pruductSellList/GetProductSkuInfoByProductId',
                        payload: {
                            id: id
                        },
                        callBack:  {
                            success: res => {
                                this.setState({
                                    editPriceVisible: true,
                                    ProductId: id,
                                    btnLoading: false
                                })}
                        }
                    })
                } else {
                        this.setState({
                            clickId: `${id}_${index}`,
                            btnLoading: false
                        })
                    }
               },
               error: res => {
                console.log(res);
               }
           }
   })
}

// 点击库存
clickQueryStockData = (id, index) => {
    let { dispatch } = this.props;
    this.setState({
      btnLoading2: true
     })
     dispatch({
        type: 'pruductSellList/IsMultiProduct',
        payload: {
            id: id
        },
        callBack: {
            success: res => {
                if(res.Data) {
                    this.setState({
                        clickId: ''
                   })
                    dispatch({
                        type: 'pruductSellList/GetProductSkuInfoByProductId',
                        payload: {
                            id: id
                        },
                        callBack: {
                            success: res => {
                              this.setState({
                                editStockVisible: true,
                                ProductId: id,
                                btnLoading2: false
                            })}
                        }
                    })
                } else {
                     this.setState({
                         clickId: `${id}_${index}`,
                         btnLoading2: false
                     })
                 }
            },
            error: res => {
             console.log(res);
            }
        }
     })
}

clickDelete =() => {
    const {selectedUserIds} = this.state;
    const { dispatch } = this.props;
    const that = this;
    if(selectedUserIds.length< 1) {
      message.error('请选择最少一个商品');
    }else {
        Modal.confirm({
            title: '商品删除请谨慎操作,确认删除?',
            okText: '删除',
            cancelText:'我再想想',
            onOk() {
                dispatch({
                    type: 'pruductSellList/DeletesProduct',
                    payload: selectedUserIds.toString(),
                    callBack: {
                        success: res => {
                          if (res.Code === 0) {
                            message.success('删除成功');
                            that.setState({
                                loading: true
                            },
                              () => {
                                that.getSearchSoldOutProductListWithPage();
                              }
                            );
                          }
                        },
                        error: res => {
                          message.error(res.Msg);
                        },
                      },
                });
            }
        })
    }
}

// tabel勾选
onSelectChange= (selectedUserIds, selectedRows) => {
  const {soldOutProductList} = this.props;
  let isChecked = null;
  if(soldOutProductList) {
    if(soldOutProductList.length === selectedUserIds.length) {
      isChecked=true
    }else{
      isChecked=false
    }
  }
    this.setState({
      selectedUserIds, selectedRows, isChecked,
      indeterminate: selectedUserIds.length && selectedUserIds.length<soldOutProductList.length
    })
}

// 全选
selectAll=()=> {
  const {soldOutProductList} = this.props;
  const {selectedRows} = this.state;
  if(soldOutProductList) {
    if(soldOutProductList.length === selectedRows.length) {
      this.onSelectChange([],[]);
      this.setState({
          isChecked:false
      })
  } else {
      const index = [];
      soldOutProductList.forEach(item=>{
        index.push(item.Id)
      });
      this.setState({isChecked:true})
      this.onSelectChange(index,soldOutProductList)
  }
  }
}

// 复制
clickCopyProduct=(id)=> {
    const { dispatch } = this.props;
    dispatch({
        type: 'pruductSellList/CopyProduct',
        payload: {
            Id: id
        },
        callBack: {
            success: res=> {
                if(res.Code ===0) {
                    message.success('复制成功');
                    this.setState({
                        loading: true
                    }, ()=> {
                        this.getSearchSoldOutProductListWithPage();
                    })
                }
            },
            error: res => {
                message.error(res.Msg)
            }
        }
    })
}

// 点击排序
clickQuerySortData =(id, index) => {
    this.setState({
        clickId: `${id}_${index}`
    })
}

  render() {
    const { loading, selectedUserIds,isChecked, ProductId,firstLoading,indeterminate} = this.state;
    const { soldOutProductList} = this.props;

    const rowSelection = {
      selectedRowKeys:selectedUserIds,
      onChange: this.onSelectChange,
    };

      const menu =(
          <Menu onClick={this.handleMenuClick}>
            {['修改标签'].map((item, index) => (
                <Menu.Item key={index}>{item}</Menu.Item>
            ))}
          </Menu>
      );

    return (
      <Fragment>
        {/* <HeaderTab
          _this={this}
          type="slider"
          activeId={this.state.activeId}
          onChange={this.onTabChange}
          tabs={this.state.tabs}
        >
        </HeaderTab> */}
        <Spin spinning={firstLoading}>
        <Card className="popconfirm" bordered={false}>
        <Button type="primary" onClick={this.releaseGoods} style={{marginBottom: 16}}>发布商品</Button>
        <div style={{background:'#fafafa',marginBottom:16,paddingTop:16,paddingRight:16,boxSizing:'border-box'}}>
                <div className="tableListForm">{this.renderForm()}</div>
            </div>
          <div className={styles.NavButtons}>
            <Checkbox checked={isChecked} onChange={this.selectAll} style={{marginLeft: 16}} indeterminate={indeterminate}>
                    <span style={{marginRight: 8}}>当页全选</span>
            </Checkbox>
            <Button onClick={this.clickOffline}>批量下架</Button>
            <Button onClick={this.clickChangeClassfy}>修改分类</Button>
            <Button onClick={this.clickDelete}>删除商品</Button>
            <Dropdown overlay={menu}>
                <Button>更多 <Icon type="down" /></Button>
            </Dropdown>
          </div>
          <Table
            rowSelection={rowSelection}
            loading={loading}
            pagination={this.state.pagination}
            dataSource={soldOutProductList}
            onChange={this.onTableChange}
            rowKey={record => record.Id}
            className={styles.tableBody}
            onRow={(record, index) => {
                return {
                  onMouseEnter: (event) => {
                      this.setState({
                          selectRow: record.Id
                      })
                  },
                  onMouseLeave: (event) => {
                    this.setState({
                      selectRow: '',
                    })
                },
                };
              }}
            columns ={[
                {
                  title: '商品名称',
                  dataIndex: 'Name',
                  key: 'Name',
                  width: '22%',
                  render: (text, record) => (
                    <List.Item>
                      <List.Item.Meta
                        avatar={<Avatar src={
                            this.props.oemInfo['cdnUrl'] + '/' + record.ImgUrl +'?x-oss-process=style/240'
                        } className={styles.imagesBox} />}
                        title={<div className={styles.leftName} title={record.Name}>{record.Name}</div>}
                      />
                    </List.Item>
                  ),
                },
                {
                  title: '价格',
                  dataIndex: 'SalePrice',
                  align: 'right',
                  key: 'SalePrice',
                  width: '12%',
                  sorter: (a, b) => a.SalePrice - b.SalePrice,
                  render: (text, data) => {
                    return (
                        <div>
                            <span>￥{data.SalePrice.toFixed(2)}</span>
                                <div
                                     style={
                                        this.state.selectRow === data.Id?{visibility: 'visible'}:
                                        this.state.clickId==`${data.Id}_1`?{visibility: 'visible'}:{visibility: 'hidden'}
                                    }
                                >
                                    <Popconfirm
                                        placement="bottom"
                                        icon={false}
                                        title={this.editSalePrice(data.SalePrice)}
                                        onConfirm={() => this.updateSProductPrice(data.Id, data.SalePrice)}
                                        onCancel={() => this.setState({clickId: ''})}
                                        okText="保存"
                                        cancelText="取消"
                                        visible={this.state.clickId==`${data.Id}_1`?true:false}
                                        getPopupContainer={() => document.querySelector(`.popconfirm`)}
                                    >
                                        <Icon type={this.state.selectRow === data.Id?this.state.btnLoading?"loading":"edit":'edit'} style={{cursor: 'pointer'}} onClick={()=>this.clickQueryPriceData(data.Id,1)}/>
                                    </Popconfirm>
                                </div>
                        </div>
                    );
                }
                },
                {
                  title: '总库存',
                  dataIndex: 'Stock',
                  align: 'right',
                  key: 'Stock',
                  width: '12%',
                  sorter: (a, b) => a.Stock - b.Stock,
                  render: (text, data) => {
                    return (
                        <div>
                            <span>{data.Stock}</span>
                              <div
                                style={
                                    this.state.selectRow === data.Id?{visibility: 'visible'}:
                                    this.state.clickId==`${data.Id}_2`?{visibility: 'visible'}:{visibility: 'hidden'}
                                }
                              >
                                <Popconfirm
                                    placement="bottom"
                                    icon={false}
                                    title={this.editStock(data.Stock)}
                                    onConfirm={() => this.updateProductStock(data.Id, data.Stock)}
                                    onCancel={() => this.setState({clickId: ''})}
                                    okText="保存"
                                    cancelText="取消"
                                    visible={this.state.clickId==`${data.Id}_2`?true:false}
                                    getPopupContainer={() => document.querySelector(`.popconfirm`)}
                                >
                                    <Icon type={this.state.selectRow === data.Id?this.state.btnLoading2?"loading":"edit":'edit'} style={{cursor: 'pointer'}} onClick={()=>this.clickQueryStockData(data.Id,2)}/>
                                </Popconfirm>
                              </div>
                        </div>
                    );
                }
                },
                {
                    title: '销量',
                    dataIndex: 'SaleNum',
                    align: 'right',
                    key: 'SaleNum',
                    width: 90,
                    sorter: (a, b) => a.SaleNum - b.SaleNum,
                },
                {
                    title: '排序',
                    dataIndex: 'Sort',
                    align: 'right',
                    key: 'Sort',
                    width: '10%',
                    sorter: (a, b) => a.Sort - b.Sort,
                    render: (text, data) => {
                        return (
                            <div>
                                <span>{data.Sort}</span>
                                <div
                                     style={
                                        this.state.selectRow === data.Id?{visibility: 'visible'}:
                                        this.state.clickId==`${data.Id}_3`?{visibility: 'visible'}:{visibility: 'hidden'}
                                    }
                                >
                                    <Popconfirm
                                        placement="bottom"
                                        icon={false}
                                        title={this.editSort(data.Sort)}
                                        onConfirm={() => this.updateProductSort(data.Id, data.Sort)}
                                        onCancel={() => this.setState({clickId: ''})}
                                        okText="保存"
                                        cancelText="取消"
                                        visible={this.state.clickId==`${data.Id}_3`?true:false}
                                        getPopupContainer={() => document.querySelector(`.popconfirm`)}
                                    >
                                        <Icon type="edit" style={{cursor: 'pointer'}} onClick={()=>this.clickQuerySortData(data.Id, 3)}/>
                                    </Popconfirm>
                                </div>
                            </div>
                        );
                    }
                },
                {
                    title: '创建时间',
                    dataIndex: 'CreateTime',
                    align: 'left',
                    key: 'CreateTime',
                    width: 130,
                  },

                {
                  title: '操作',
                  key: 'action',
                  render: (text, data) => (
                    <span>
                        <span
                            className={`${styles.brandColor} ${styles.pointer}`}
                            onClick={() => this.editPage(data.Id)}
                            >
                            编辑
                        </span>
                        <Divider type="vertical" />
                        <Fragment>
                            <Popover content={this.showQRcode(data)} trigger="click" placement="bottom" onVisibleChange={(visible)=>this.handleVisibleChange(visible,data)}>
                            <span className={`${styles.brandColor} ${styles.pointer}`}>推广</span>
                            </Popover>
                            <Divider type="vertical" />
                        </Fragment>
                        <Fragment>
                            <span
                                className={`${styles.brandColor} ${styles.pointer}`}
                                onClick={() => this.clickCopyProduct(data.Id)}
                            >
                            复制
                            </span>
                        </Fragment>
                    </span>
                  ),
                  align: 'right',
                  width: 150,
                },
              ]}
          />
        </Card>
        </Spin>

        <ChangeLebal
          ref={e => {
              this.changeLebal = e;
          }}
        />
         <ChangeClassify
            ref= {e => {
                this.changeClassify = e;
            }}
        />
         <ChangePrice
            _thisSoldOut={this}
            editPriceVisible={this.state.editPriceVisible}
            ProductId={ProductId}
        />
        <ChangeStock
            _thisSoldOut={this}
            editStockVisible={this.state.editStockVisible}
            ProductId={ProductId}
        />
      </Fragment>
    );
  }
}

export default connect(({ pruductSellList, global, loading }) => ({
    oemInfo: global.oemInfo,
    productGroupList: pruductSellList.productGroupList,
    productTagList: pruductSellList.productTagList,
    soldOutProductList: pruductSellList.soldOutProductList,
    productSkuInfo: pruductSellList.productSkuInfo,
    sourceDatas:pruductSellList.sourceData,
    loading2: loading.effects['orderPickUp/GetWxCode'],
}))(Pagination);
